package net.tp.algo.graph.shortestpath;

import net.tp.algo.graph.Graph;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 *
 *
 *
 */
public class BFS {

    private int[] distanceTo;

    public BFS(Graph graph, int source) {
        this.distanceTo = new int[graph.order()];
        Arrays.fill(distanceTo, Integer.MAX_VALUE);

        this.distanceTo[source] = 0;

        boolean[] marked = new boolean[graph.order()];
        Queue<Integer> queue = new LinkedList<>();
        queue.add(source);
        marked[source] = true;

        while (!queue.isEmpty()) {
            int u = queue.remove();
            for (int w : graph.adjacents(u)) {
                if (!marked[w]) {
                    marked[w] = true;
                    queue.add(w);
                    this.distanceTo[w] = this.distanceTo[u] + 1;
                }
            }
        }
    }

    public int distanceTo(int w) {
        return this.distanceTo[w];
    }

}
